﻿using System;
using System.Collections.Generic;
using UI;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

[DefaultExecutionOrder(100)]
public class GameManager : MonoBehaviour
{
    public static Transform SceneRoot => _instance.m_currentScene.transform;
    
    private static GameManager _instance;

    public int startIndex;

    public List<GameObject> scenePrefabList;
    public List<string> startEndScenarioList;
    
    private int m_currentIndex;
    private GameObject m_currentScene;
    private PlayableDirector m_currentDirector;

    private void Awake()
    {
        _instance = this;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.T))
        {
            InventoryManager.AddItem(EItemType.七巧板);
        }
    }

    public void StartGame()
    {
        //图1
        LoadMapInternal(startIndex);
    }
    private void OnStartAnimEnd(PlayableDirector obj)
    {
        m_currentDirector.stopped -= OnStartAnimEnd;
        
        PlayerController.SetPause(false);
        UI_ScenarioPanel.StartScenario(startEndScenarioList[m_currentIndex]);
    }
    
    private void LoadMapInternal(int index)
    {
        if (m_currentScene != null)
        {
            GameObject.Destroy(m_currentScene);
            m_currentDirector = null;
        }
        m_currentIndex = index;
        m_currentScene = GameObject.Instantiate(scenePrefabList[index]);
        if (m_currentScene.TryGetComponent(out m_currentDirector))
        {
            PlayerController.SetPause(true);
            m_currentDirector.Play();
            m_currentDirector.stopped += OnStartAnimEnd;
        }
        else
        {
            var scenario = startEndScenarioList[m_currentIndex];
            if (!string.IsNullOrEmpty(scenario)) UI_ScenarioPanel.StartScenario(scenario);
        }
    }

    public static void LoadMap(int index)
    {
        _instance.LoadMapInternal(index);
    }
}